<template>
  <div id="timeline-wrapper">
    <div id="timeLine_content">
      <div class="timeline-header">
        <div class="now-time">
          <div class="now-year now-word">{{nowTickTime.year}}</div>
          <div class="now-month now-word">{{nowTickTime.month}}</div>
          <div class="now-day now-word">{{nowTickTime.day}}</div>
        </div>
        <div class="play-content">
          <div class="now-time-interval">
            <el-dropdown @command="intervalSelect">
              <span class="el-dropdown-link">
                {{whatTimeInterval}}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="Year">Year</el-dropdown-item>
                <el-dropdown-item command="Season">Season</el-dropdown-item>
                <el-dropdown-item command="Month">Month</el-dropdown-item>
                <el-dropdown-item command="Week">Week</el-dropdown-item>
                <el-dropdown-item command="Day">Day</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="play-btn" :class="{'pause-btn':isPlay,'hide-play-btn':isTwoTick}" v-loading.fullscreen.lock="playLoading" element-loading-background="rgba(0, 0, 0, 0.8)" @click="playTime"></div><!--playTimeLine-->
        </div>
      </div>
      <div class="startTime-select now-time-select">
        <el-date-picker type="date" v-model="startTime" align="left" clearableD size="small" format="yyyy-MM-dd" class="horizontal-input"
                        value-format="yyyy-MM-dd" placeholder="请选择时间" v-bind:style="{width:'100px',margin:timelineSelecterMarginStyle}" :readonly="timeRead"
                        @change="changeDate($event,'start')">
        </el-date-picker>
      </div>
      <div :id="'canvas_parent'+whatScene" class="draw-time-line">

          <!--<canvas id="timeline_canvas" class="time-line-canvas"></canvas>-->

        <canvas :id="'timeline_tick_canvas'+whatScene" class="time-line-canvas"></canvas>
        <img src="./image/tick-slide.png" style="display: none;" :id="'tick_slide_Image'+whatScene"/>
        <img :src="AActiveTick" style="display: none;" :id="'A_tick_slide_Image'+whatScene"/>
        <img :src="BDisabledTick" style="display: none;" :id="'B_tick_slide_Image'+whatScene"/>
       <!-- </ul>-->
      </div>
      <div class="endTime-select now-time-select">
        <el-date-picker type="date" v-model="endTime" align="left" clearable size="small" format="yyyy-MM-dd" class="horizontal-input"
                        value-format="yyyy-MM-dd" placeholder="请选择时间" v-bind:style="{width:'100px',margin:timelineSelecterMarginStyle}" :readonly="timeRead"
                        @change="changeDate($event,'end')">
        </el-date-picker>
      </div>
    </div>
  </div>
</template>
<script>
  /*
  * 时间轴组件
  * by lishuang
  * */
  import AActiveTick from '@/assets/images/timeline/A-tick-active.png';
  import BDisabledTick from '@/assets/images/timeline/B-tick-disabled.png';
  import BActiveTick from '@/assets/images/timeline/B-tick-active.png';
  import ADisabledTick from '@/assets/images/timeline/A-tick-disabled.png';
  export default {
    name: 'LsTimeLine',
    props: {
      scene:'',    //什么场景下用到的时间轴插件,相当于id，唯一性
      data:Array,   //播放内容的数据
      startDate:String,    //开始时间
      endDate:String,    //时间轴上结束时间
      isTwoTick:false,    //是否显示两个tick标签
      BStartDate:String,   //BTick的开始时间    //isTwoTick是true的时候，传进来
      BEndDate:String,     //BTick的结束时间    //isTwoTick是true的时候，传进来
      timeLineInterval:String,   //时间轴的时间间隔
      playStartDate:String,    //播放时间段开始的时间
      playEndDate:String,    //播放时间段结束的时间
      playLoading:Boolean,   //播放过程中加载loading

    },
    data() {
      return {

        AActiveTick:AActiveTick,   //需要两个Tick按钮时，ATick按钮激活状态
        BDisabledTick:BDisabledTick, //Btick按钮的不可点击状态
        BActiveTick:BActiveTick,    //BTick按钮激活状态
        ADisabledTick:ADisabledTick,   //ATick不可点击状态

        timelineSelecterMarginStyle:'34px 0',
        myScroll:{},
        timeline:{},
        startTime:'2019-01-01',
        endTime:'2019-12-31',
        timeRead:false,
        whatTimeInterval:'Day',
        /*canvas:{},     //时间轴画布
        context:{},*/
        tickCanvas:{},    //刻度标签画布
        tickContext:{},
        layerList:[],  //所有图层列表数据


        monthList:{'1':"JAN",'2':"FEB",'3':"MAR", '4':"APR",'5':"MAY",'6':"JUN",'7':"JUL",'8':"AUG", '9':"SEP", '10':"OCT",'11':"NOV", '12':"DEC"},

        // 固定值
        MONTH_DAYS : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],

        // Canvas 信息
        showRegionWidth:0,  //整个展示区域的宽度
        showRegionHeight:0,

        // 鼠标事件信息
        startPos:{x:'',y:''},
        endPos:{x:'',y:''},
        isMouseDown:false,

        // 时间轴信息
        timelineAllWidth:0,   //整个时间轴的宽度
        timeLineStartX :0,    //绘制时间轴开始的X坐标
        currentScale : 1,     //1：10年一个单位，2：一年，及月为时间间隔， 3：日为时间间隔
        canBeScroll : true,

        // 配置数据
        // 最小单位间隔
        tickLineInterval:15,
        tickValueHeight:20,//时间轴刻度值绘制的位置的y坐标

        // 时间轴 时间范围[originYear, lastYear)
        originYear:2010,
        lastYear:2050,

        tickImage:{},   //刻度按钮的图片
        tickImageClicked : false,
        tickImageIndex : 0,    //时间轴刻度按钮的下标
        tickImageTime : "",
        maxIndex : 0,

        timeInterval:{},   //定义一个定时器
        isPlay:false,   //时间轴是否播放

        layerClipHeight:5,  //每个图层时间段的高度

        nowTickTime:{    //当前时间刻度按钮指向的时间
          year:'',
          month:'',
          day:''
        },

        //两个tick游标的时候，Atick默认是点击状态
        ATickIsActive:true,
        BTickIsActive:false,
        showTwoTick:false,

        ATickImage:{},
        BTickImage:{},
        ATickImageClicked:false,
        BTickImageClicked:false,
        BTickImageIndex:0,
        BTickImageTime:'',
        BStartTime:'2019-02-01',
        BEndTime:'2019-12-31',
        isBTickActive:false,
        BNowTickTime:{
          year:'',
          month:'',
          day:''
        },

        timelineInit:true,

        playStartT:'2019-01-01',
        playEndT:'2019-12-31',

        isPause:false,    //是否是暂停状态
        isFirstClickPlay:true,   //是否是第一次点击播放功能
        playTimeIsChange:false,   //播放的时间是否变化

        productPlayIndex:0,   //产品场景用于播放的index

        whatScene:'',


      };
    },
    watch: {

      scene: {
        handler:function (val) {
          this.whatScene = val;
        },
        immediate: true,
      },
      data:{
        handler:function (val) {
          this.layerList = val;
          if (!this.timelineInit){
            this.drawTimeTick();
          }
        },
        immediate: true,
        deep:true
      },

      startDate:{
        handler:function (val) {
          if (val) {
            this.startTime = val;
            //console.log('startDate');
            if (this.timelineInit) this.init();
          }

        },
        immediate: true,
      },
      endDate:{
        handler:function (val) {
          if (val) {
            this.endTime = val;
            if (!this.timelineInit) this.init();
          }

        },
        immediate: true,
      },
      BStartDate:{
        handler:function (val) {
          if (val) {
            this.BStartTime = val;
          }

        },
        immediate: true,
      },
      BEndDate:{
        handler:function (val) {
          if (val) {
            this.BEndTime = val;

            if(this.showTwoTick && this.isBTickActive) this.init();
          }

        },
        immediate: true,
      },

      playStartDate:{
        handler:function (val) {
          if (val) {
            this.playStartT = val;
            this.isPlay = false;
            this.playTimeIsChange = true;
          }
        },
        immediate: true,
      },
      playEndDate:{
        handler:function (val) {
          if (val) {
            this.playEndT = val;
            this.isPlay = false;
            this.playTimeIsChange = true;
          }
        },
        immediate: true,
      },
      isTwoTick:{
        handler:function (val) {
          //if (!this.timelineInit) {
            let that = this;
              this.showTwoTick=val;
              this.$nextTick(()=> {
                  that.timelineInit = true;
                  that.init();
              })
              /*setTimeout(function () {

              },100);*/

          //}
        },
        immediate: true,
      },
      timeLineInterval: {
        handler:function (val) {

          if (val == '' ||!val) this.whatTimeInterval='Day';
          else this.whatTimeInterval = val;
        },
        immediate: true,
      },
    },
    mounted() {
       // console.log('lsTImelien');
      //this.init();

    },
    methods: {
      init() {
          //console.log('line init');
        let that = this;
        setTimeout(function () {
          let width = document.getElementById('canvas_parent'+that.whatScene).offsetWidth;
          let height = document.getElementById('canvas_parent'+that.whatScene).offsetHeight;
          that.showRegionWidth = width;
          that.showRegionHeight = height;
          /* this.canvas = document.getElementById('timeline_canvas');
           this.context = this.canvas.getContext('2d');*/
          that.tickCanvas = document.getElementById('timeline_tick_canvas'+that.whatScene);
          that.tickCanvas.addEventListener('mousedown', that.tickCanvasClickEvent.bind(that));   // 点击事件
          that.tickCanvas.addEventListener('mousemove', that.tickCanvasmousemoveEvent.bind(that));   // 点击事件
          that.tickCanvas.addEventListener('mouseup', that.tickCanvasmouseupEvent.bind(that));   // 点击事件
          that.tickCanvas.addEventListener('mousewheel', that.tickCanvasmousewheelEvent.bind(that),false);   // 点击事件
          that.tickCanvas.addEventListener('dblclick', that.tickCanvasmouseDbClickEvent.bind(that),false);   // 双击事件
          that.tickContext = that.tickCanvas.getContext('2d');

          // 设定默认值
          that.currentScale = that.getScaleFromTimeInterval();


          //初始化tickImage游标
          that.initTickImage();


          // 更新时间轴长度
          that.updateTimeLineLength();

          // 更新起始位置，默认居中显示
          that.updateTimeLinePositionFromYMDString(that.tickImageTime);

          if(that.timelineInit){
            // 开始绘制
            that.setCanvasWH(width,height);
            that.timelineInit=false;
          } else {
            that.resizeCanvas();
          }

        },200);

      },

      initTickImage() {
        if (this.isTwoTick) {
          this.ATickImage = document.getElementById('A_tick_slide_Image'+this.whatScene);
          this.BTickImage = document.getElementById('B_tick_slide_Image'+this.whatScene);
          //this.tickImage = this.ATickImage;
          this.BTickImageTime = this.BStartTime;

          this.tickImageTime = this.startTime;
          //console.log('A',this.ATickImage);
          //console.log('B',this.BTickImage);
          this.tickImage = null;
        } else {
          this.tickImage = document.getElementById('tick_slide_Image'+this.whatScene);
          this.tickImageTime = this.startTime;
          this.ATickImage = null;
          this.BTickImage = null;
        }
      },

      //resize时间轴展示区域的大小
      resizeCanvas() {
        let width = document.getElementById('canvas_parent'+this.whatScene).offsetWidth;
        let height = document.getElementById('canvas_parent'+this.whatScene).offsetHeight;

        this.tickCanvas.width = width;
        this.tickCanvas.height = height;

     /*   this.jq('.now-word').css('margin-top',(height - 30) / 2+'px');
        this.jq('.now-time-interval').css('margin-top',(height - 62) / 2+'px');*/

        this.timelineSelecterMarginStyle = (height-32) / 2+'px 0px';

        this.showRegionWidth = width;
        this.showRegionHeight = height;

        this.drawTimeTick();

      },

      getScaleFromTimeInterval() {
        if (this.whatTimeInterval == 'Day') {
          return 5;
        } else if (this.whatTimeInterval == 'Month') {
          return 3;
        } else if (this.whatTimeInterval == 'Year') {
          return 1;
        } else if (this.whatTimeInterval == 'Season') {
          return 2;
        } else if (this.whatTimeInterval == 'Week') {
          return 4;
        }
      },

      //判断是哪个时间间隔
      judgeWhatInterval() {
        let scale = this.getScaleFromTimeInterval();
        this.scaleTimeline(scale);
      },

      // 给定年月获取有多少天； 注意Month 是 0 - 11 的数字
      getMonthDays(year, month){
        if (month < 0 && month > 11){
          /// 错误参数
          return 0;
        }
        let days = this.MONTH_DAYS[month];
        if(month == 1 && this.isRunNian(year)) ++days;
        return days;
      },

      // 获取时间轴显示多少年
      getYearNum() {
        return this.lastYear - this.originYear;
      },

      //判断是否是闰年
      isRunNian(year) {
        return ((((year % 4)==0) && ((year % 100)!=0)) || ((year % 400)==0));
      },

      //根据年份返回每年的天数
      getYearDays(year) {
        if (this.isRunNian(year)) return 366;
        else return 365;
      },

      updateTimeLineLength() {
        this.timelineAllWidth = 0;
        let yearNum = this.getYearNum();
        if (this.currentScale == 1){
          this.tickLineInterval = 20;
          this.maxIndex = yearNum;
          this.timelineAllWidth = this.tickLineInterval * yearNum;
        }else if (this.currentScale == 2) {
          this.tickLineInterval = 20;
          this.maxIndex = yearNum * 4;
          this.timelineAllWidth = this.tickLineInterval * yearNum * 4;
        }else if (this.currentScale == 3) {
          this.tickLineInterval = 15;
          this.maxIndex = yearNum * 12;
          this.timelineAllWidth = this.tickLineInterval * yearNum * 12;
        }else if (this.currentScale == 4) {
          this.tickLineInterval = 3;
          for (let year = this.originYear; year < this.lastYear; ++year){
            this.timelineAllWidth += this.tickLineInterval * this.getYearDays(year);
            this.maxIndex += this.getYearDays(year);
          }
        }else if (this.currentScale == 5) {
          this.tickLineInterval = 15;
          for (let year = this.originYear; year < this.lastYear; ++year){
            this.timelineAllWidth += this.tickLineInterval * this.getYearDays(year);
            this.maxIndex += this.getYearDays(year);
          }
        }else{
          // 错误 不应该到达这里
        }
        // 如果Timeline长度小于Canvas 长度， 禁止拖拽滚动滚动
        if (this.timelineAllWidth <= this.showRegionWidth) {
          this.canBeScroll = false;
        }else {
          this.canBeScroll = true;
        }
      },

      getWeekFromYMD(year, month, day) {
        let week = new Date(year+'-'+month+'-'+day).getDay();
        if (week == 0) week = 7;
        return week;
      },

      // 根据传入的年月日获取时间轴对应刻度的下标index
      // year originYear - lastYear
      // month 1-12
      // day 1-31
      getIndexFromYMD(year, month, day) {
        if (year < this.originYear || (month < 1 && month > 12) || (day < 0 && day > 31)) {
          // 错误的参数
          return -1;
        }

        if (this.currentScale == 1){     //year
          return year - this.originYear;
        }else if (this.currentScale == 2) {     //season
          return (year - this.originYear) * 4 + Math.floor((month - 1)/3);
        }else if (this.currentScale == 3) {     //month
            return (year - this.originYear) * 12 + (month - 1);
        }else if (this.currentScale == 4){  /// week
          let index = 0;
          for (let y = this.originYear; y < year; ++y) {
            index += 365;
            if (this.isRunNian((y))) index += 1;
          }
          for (let m = 0; m < month -1; ++m){
            index += this.getMonthDays(year, m);
          }
          let week = this.getWeekFromYMD(year, month, day);
          let tempIndex = index + (day -1);
         // console.log("week " , week);
          return tempIndex - week + 1;
        }else if (this.currentScale == 5){    //day
          let index = 0;
          for (let y = this.originYear; y < year; ++y) {
            index += 365;
            if (this.isRunNian((y))) index += 1;
          }
          for (let m = 0; m < month -1; ++m){
            index += this.getMonthDays(year, m);
          }
          return index + (day -1);
        }else {
          // 不应该到达此处
          return 0;
        }
      },

      //传入真实时间轴上的位置返回当前位置对应的刻度线的下标
      getIndexFromTimelinePosX(x) {
        let xOnTimeline = x;
        if (xOnTimeline < 0) xOnTimeline = 0;
        if (xOnTimeline > this.timelineAllWidth) xOnTimeline = this.timelineAllWidth;
        return Math.floor(xOnTimeline/this.tickLineInterval);
      },

      //根据天数返回当前年月日
      getTimeFromDays(alldays) {
        if(alldays <= 0) {
          return {year:this.originYear, month:1, day: 1};
        }

        let result = {year:0, month:0, day:0};
        let over = false;
        for (let year = this.originYear; year < this.lastYear + 1; ++year) {
          let daysOfYear = this.getYearDays(year);
          if (alldays > daysOfYear) {
            alldays -= daysOfYear;
          }else{
            result.year = year;
            for (let month = 0; month < 12; ++ month) {
              let monthDays = this.getMonthDays(year, month);
              if (monthDays < alldays){
                alldays -= monthDays;
              }else{
                result.month = month + 1;
                result.day = alldays;
                over = true;
                break;
              }
            }
          }
          if (over) break;
        }
        return result;
      },

      //根据index刻度线的下标返回时间
      getTimeFromIndex(index) {
        let defaultDay = 1;
        let defaultMonth = 1;
        let result = {year:0, month:0, day:0};
        if (this.currentScale == 1){   /// year
          result.month = defaultMonth;
          result.day = defaultDay;
          result.year = this.originYear + index;
        }else if (this.currentScale == 2) {  // season
          result.day = defaultDay;
          result.year = Math.floor(index / 4) + this.originYear;
          result.month = (index % 4) * 3 + 1;
        }else if (this.currentScale == 3) { /// month
          result.day = defaultDay;
          result.year = Math.floor(index / 12) + this.originYear;
          result.month = index % 12 + 1;
        }else if(this.currentScale == 4 || this.currentScale == 5) { /// week and Day
          let alldays = index + 1;
          result = this.getTimeFromDays(alldays);
        }
        return result;
      },

      needDrawReal(index) {
        if (this.currentScale == 1){   // year
          return (this.originYear + index) % 10 == 0
        }else if (this.currentScale == 2) {  // season
          return index % 4 == 0
        }else if (this.currentScale == 3) { // month
          return index % 12 == 0
        }else if(this.currentScale == 4) { // week
          let res = this.getTimeFromIndex(index);
          //console.log('res: ',res);
          return res.day == 1;
        }else if(this.currentScale == 5) { // day
          let res = this.getTimeFromIndex(index);
          //console.log('res: ',res);
          return res.day == 1;
        }
      },

      /// 是否画虚线， 对周特殊处理
      needDrawDottedLine(index) {
        if (this.currentScale == 1 || this.currentScale == 2 || this.currentScale == 3 || this.currentScale == 5) return true;

        let res = this.getTimeFromIndex(index);

        let week = this.getWeekFromYMD(res.year, res.month, res.day);
        return week == 1;   //week时，确定每个星期一绘制虚线
      },

      // 将时间轴上的位置转换到canvas 坐标【0-regionShowWidth】
      getPosXOnCanvas(x) {
        let xOnTimeline = x;
        if (xOnTimeline < 0) xOnTimeline = 0;
        if (xOnTimeline > this.timelineAllWidth) xOnTimeline = this.timelineAllWidth;
        /// 这里可能会超过显示区域， 需要判断是不是在显示区域再进行下一步操作
        return xOnTimeline - this.timelineStartX;
      },

      // 传入canvas内的 x坐标 范围距离时间轴起点的偏移长度
      getPosXOnTimeline(x) {
        let xOnCanvas = x;
        if (xOnCanvas < 0) xOnCanvas = 0;
        if (xOnCanvas > this.showRegionWidth) xOnCanvas = this.showRegionWidth;
        let result = xOnCanvas + this.timelineStartX;

        if (result > this.timelineAllWidth) result = this.timelineAllWidth;
        if (result < 0) result = 0;

        return result;
      },

      getYMDFromString(time) {
        if (time == null) return 0;
        let array = time.split('-');
        let month=0;
        let day = 0;
        if (array.length <3) {
          return 0;
        }
        if (array[1].charAt(0) == 0) {
          month = array[1].charAt(1);
        } else {
          month = array[1];
        }
        if (array[2].charAt(0) == 0) {
          day = array[2].charAt(1);
        } else {
          day = array[2];
        }
        return {year:array[0],month:month,day:day};
      },

      updateTimeLinePositionFromYMDString(time) {
        let result = this.getYMDFromString(time);
        if (result ==0 || result == null) {
          console.log('获取年月日数值错误！');
          return;
        }
        return this.updateTimeLinePositionFromYMD(result.year,result.month,result.day);
      },

      // 将传入的年月日 对应的刻度 显示在canvas 中央
      updateTimeLinePositionFromYMD(year, month, day) {
        if (year < this.originYear || (month < 1 && month > 12) || (day < 0 && day > 31)) {
          /// 错误的参数
          return;
        }

        /// 当timeline 长度 小于canvas 长度时 永远居中显示
        if (this.timelineAllWidth <= this.showRegionWidth) {
          this.updateTimeLinePositionView(this.timelineAllWidth / 2);
          return;
        }

        let index = this.getIndexFromYMD(year, month, day);
        if (index < 0) return;
        let timelinePosX = index * this.tickLineInterval;
        this.updateTimeLinePositionView(timelinePosX);
      },

      // 更新显示区域，timelinePosX为时间轴坐标，该函数会将时间轴坐标显示在canvas中央
      updateTimeLinePositionView(timelinePosX) {
        let x = timelinePosX;
        if (x < 0) x = 0;
        else if (x > this.timelineAllWidth) x = this.timelineAllWidth;

        this.timelineStartX = x - this.showRegionWidth / 2;
      },

      // realLine : true 绘制实线 false 绘制虚线
      drawLittleTick(posx, realLine) {
          let endHeight = this.tickCanvas.height - this.tickValueHeight;
          this.tickContext.beginPath();
          if (realLine){
            this.tickContext.strokeStyle = '#ffffff';
          }else{
            this.tickContext.strokeStyle = '#3e3d3f';
          }
          this.tickContext.moveTo(posx, endHeight);
          this.tickContext.lineTo(posx, 0);
          if (!realLine) {
            this.tickContext.setLineDash([3,3,3]);
          } else {
            this.tickContext.setLineDash([]);
          }
          this.tickContext.closePath();
          this.tickContext.stroke();
      },

      // 绘制图层的时间段
      drawTimeClip(startTime, endTime,drawHeight,layerIsShow) {

        let startResult =  this.getYMDFromString(startTime);
        if(startResult == 0 || startResult == null || startResult == undefined){
          return;
        }

        let endResult =  this.getYMDFromString(endTime);
        if(endResult == 0 || endResult == null || endResult == undefined){
          return;
        }

        let startImageIndex = this.getIndexFromYMD(startResult.year,startResult.month,startResult.day);
        let endImageIndex = this.getIndexFromYMD(endResult.year,endResult.month,endResult.day);

        let startImagePosX = startImageIndex * this.tickLineInterval;
        let startCanvasPosX = this.getPosXOnCanvas(startImagePosX);

        let endImagePosX = endImageIndex * this.tickLineInterval;
        let endCanvasPosX = this.getPosXOnCanvas(endImagePosX);
        let width = endCanvasPosX - startCanvasPosX;

        //console.log("startwidth " + startCanvasPosX + " endPoxX " + endCanvasPosX);

        if (layerIsShow) {
          this.tickContext.fillStyle='#34455c';
        } else {
          this.tickContext.fillStyle='#272727';
        }
        //console.log(startCanvasPosX,drawHeight,width,this.layerClipHeight);
        this.tickContext.fillRect(startCanvasPosX,drawHeight,width,this.layerClipHeight);
      },

      // 绘制时间轴的总方法
      drawTimeTick() {
        this.tickContext.clearRect(0,0,this.tickCanvas.width,this.tickCanvas.height);
        let endHeight = this.tickCanvas.height - this.tickValueHeight;
        //绘制底部刻度值上面的那一条横的直线
        this.tickContext.strokeStyle = '#3e3d3f';
        this.tickContext.beginPath();
        this.tickContext.setLineDash([]);
        this.tickContext.moveTo(0,endHeight);
        this.tickContext.lineTo(10000,endHeight);
        this.tickContext.closePath();
        this.tickContext.stroke();

        //保证每次重绘只绘制canvas显示区域的内容
        let startIndex = Math.floor(this.getPosXOnTimeline(0) / this.tickLineInterval);
        let endIndex = Math.ceil(this.getPosXOnTimeline(this.showRegionWidth) / this.tickLineInterval);

        //console.log('startIndex:'+startIndex+' ' + 'endIndex:'+endIndex);
        //console.log('timelineAllWidth:',this.timelineAllWidth);

        // 画质时间轴刻度
        for (let index = startIndex; index <= endIndex; ++index) {
          let posX = this.getPosXOnCanvas(index * this.tickLineInterval);
          let needDrawRealLine = this.needDrawReal(index);
          if (posX >= 0 && posX <= this.showRegionWidth ) {

            if (!needDrawRealLine) {
              if (this.needDrawDottedLine(index)) this.drawLittleTick(posX, false)
            }else {
              this.drawLittleTick(posX, true)
            }
          }

          if (needDrawRealLine) {
            let res = this.getTimeFromIndex(index);

            this.tickContext.fillStyle = '#fff';
            this.tickContext.font= '16px';
            if (this.currentScale == 1 || this.currentScale == 2 || this.currentScale == 3) {

              this.tickContext.fillText(res.year,posX-13,this.tickCanvas.height - this.tickValueHeight+15);

            }else if(this.currentScale == 4 || this.currentScale == 5){
              this.tickContext.fillText(res.year+'-'+res.month,posX-13,this.tickCanvas.height - this.tickValueHeight+15);

            }

          }

        }

        // 绘制图层的时间段
        let drawHeightPosY =0;
        for (let i = 0;i< this.layerList.length;++i) {
          let list = this.layerList[i];
          if (list.timeRange.length <=0) continue;
          if (i ==0) {
            drawHeightPosY = 3;
          } else {
            drawHeightPosY = drawHeightPosY + this.layerClipHeight +3;
          }
          for (let j =0;j<list.timeRange.length;++j) {
            let timeValue = list.timeRange[j];
            this.drawTimeClip(timeValue.startTime, timeValue.endTime,drawHeightPosY,list.show);
          }
        }

        // 绘制时间轴刻度按钮
        //如果绘制两个游标，此时绘制第二个游标
        if (this.showTwoTick) {

          if (this.ATickImage == null) return;

          let result =  this.getYMDFromString(this.tickImageTime);
          if(result == 0 || result == null || result == undefined){
            return;
          }
          this.nowTickTime.year = result.year;
          this.nowTickTime.month = this.monthList[result.month];
          this.nowTickTime.day = result.day;
          this.tickImageIndex = this.getIndexFromYMD(result.year,result.month,result.day);
          let tickImagePosX = this.tickImageIndex * this.tickLineInterval;
          let canvasPosX = this.getPosXOnCanvas(tickImagePosX);

          if (canvasPosX >= 0 && canvasPosX <= this.showRegionWidth) {

            if(this.ATickImage.complete) {
              this.tickContext.drawImage(this.ATickImage,canvasPosX - this.ATickImage.width / 2 ,0);
            } else {
              let that = this;
              that.ATickImage.onload = function(){
                that.tickContext.drawImage(that.ATickImage,canvasPosX - that.ATickImage.width / 2,0);
              };
            }
          }

          if (this.BTickImage == null) return;

          let BResult = this.getYMDFromString(this.BTickImageTime);
          if (BResult == 0 || BResult == null) return;
          this.BNowTickTime.year = BResult.year;
          this.BNowTickTime.month = this.monthList[BResult.month];
          this.BNowTickTime.day = BResult.day;
          this.BTickImageIndex = this.getIndexFromYMD(BResult.year,BResult.month,BResult.day);
          let tickImagePosX1 = this.BTickImageIndex * this.tickLineInterval;
          let canvasPosX1 = this.getPosXOnCanvas(tickImagePosX1);
          if (canvasPosX1 >= 0 && canvasPosX1 <= this.showRegionWidth) {

            if(this.BTickImage.complete) {
              this.tickContext.drawImage(this.BTickImage,canvasPosX1 - this.BTickImage.width / 2 ,0);
            } else {
              let that = this;
              that.BTickImage.onload = function(){
                that.tickContext.drawImage(that.BTickImage,canvasPosX1 - that.BTickImage.width / 2,0);
              };
            }
          }
        } else {

          if(this.tickImage == null) return;
          let result =  this.getYMDFromString(this.tickImageTime);
          if(result == 0 || result == null){
            return;
          }

          this.nowTickTime.year = result.year;
          this.nowTickTime.month = this.monthList[result.month];
          this.nowTickTime.day = result.day;
          this.tickImageIndex = this.getIndexFromYMD(result.year,result.month,result.day);

          let tickImagePosX = this.tickImageIndex * this.tickLineInterval;
          let canvasPosX = this.getPosXOnCanvas(tickImagePosX);

          if (canvasPosX >= 0 && canvasPosX <= this.showRegionWidth) {

            if(this.tickImage.complete) {
              this.tickContext.drawImage(this.tickImage,canvasPosX - this.tickImage.width / 2 ,0);
            } else {
              let that = this;
              that.tickImage.onload = function(){
                that.tickContext.drawImage(that.tickImage,canvasPosX - that.tickImage.width / 2,0);
              };
            }
          }
        }
      },

      //移动刻度游标
      moveTickImage(dx) {
        if (dx == 0) return;
        if (!this.showTwoTick) {
          let intDX = Math.floor(dx);
          this.tickImageIndex += intDX;
          if (this.tickImageIndex < 0) this.tickImageIndex = 0;
          if (this.tickImageIndex >= this.maxIndex) this.tickImageIndex = this.maxIndex - 1;
          let result = this.getTimeFromIndex(this.tickImageIndex);

          if (this.currentScale == 4) {
            this.tickImageIndex = this.getIndexFromYMD(result.year, result.month, result.day);
            result = this.getTimeFromIndex(this.tickImageIndex);
          }
          this.tickImageTime = result.year + '-' +(result.month<10?'0'+result.month:result.month)+'-' +(result.day<10?'0'+result.day:result.day);

        } else {
          if (this.ATickImageClicked) {
            let intDX = Math.floor(dx);
            this.tickImageIndex += intDX;
            if (this.tickImageIndex < 0) this.tickImageIndex = 0;
            if (this.tickImageIndex >= this.maxIndex) this.tickImageIndex = this.maxIndex - 1;
            let result = this.getTimeFromIndex(this.tickImageIndex);

            if (this.currentScale == 4) {
              this.tickImageIndex = this.getIndexFromYMD(result.year, result.month, result.day);
              result = this.getTimeFromIndex(this.tickImageIndex);
            }
            this.tickImageTime = result.year + '-' +(result.month<10?'0'+result.month:result.month)+'-' +(result.day<10?'0'+result.day:result.day);

          } else if (this.BTickImageClicked) {

            let intDX = Math.floor(dx);
            this.BTickImageIndex += intDX;
            if (this.BTickImageIndex < 0) this.BTickImageIndex = 0;
            if (this.BTickImageIndex >= this.maxIndex) this.BTickImageIndex = this.maxIndex - 1;
            let result = this.getTimeFromIndex(this.BTickImageIndex);

            if (this.currentScale == 4) {
              this.BTickImageIndex = this.getIndexFromYMD(result.year, result.month, result.day);
              result = this.getTimeFromIndex(this.BTickImageIndex);
            }
            this.BTickImageTime = result.year + '-' +(result.month<10?'0'+result.month:result.month)+'-' +(result.day<10?'0'+result.day:result.day);
          }
        }


        // 重新绘制整个画布
        this.drawTimeTick();
      },


      //滚动时间轴
      moveTimeline(dx) {
        if (!this.canBeScroll) return;
        // 平移时间轴
        this.timelineStartX += dx;

        if (this.timelineStartX <= -this.showRegionWidth / 2) this.timelineStartX = -this.showRegionWidth / 2;
        if (this.timelineStartX >= this.timelineAllWidth -this.showRegionWidth / 2) this.timelineStartX = this.timelineAllWidth -this.showRegionWidth / 2;

        //重新绘制整个画布
        this.drawTimeTick();
      },

      scaleTimeline(scale) {
        //debugger;
        if (scale < 1) scale = 1;
        if (scale > 5) scale = 5;
        if (scale == this.currentScale) return;
        this.currentScale = scale;

        let off = this.getPosXOnTimeline(this.showRegionWidth/2);
        let ratio = off / this.timelineAllWidth;

        // 重新总长度
        this.updateTimeLineLength();

        // 缩放保持原来中点位置不变
        let newOff = ratio * this.timelineAllWidth;
        // 如果Timeline长度 相遇 canvas， 直接将timeline居中显示
        if (this.timelineAllWidth <= this.showRegionWidth) {
          newOff = this.timelineAllWidth / 2;
        }
        this.updateTimeLinePositionView(newOff);

        this.stopPlayTimeLine();

        // 重新绘制整个画布
        this.drawTimeTick();
      },


      positionInRect(pos, rect) {
        if (pos.x < rect.x || pos.y < rect.y || pos.x > rect.x + rect.w || pos.y > rect.y + rect.h)
          return false;
        return true;
      },

      tickCanvasmouseDbClickEvent(e) {
        let that = this;

        /*if (this.showTwoTick) {
          if (this.isBTickActive) this.BTickImageClicked=true;
          else  this.ATickImageClicked=true;
        }*/
        let pos =  that.windowToCanvas(e.clientX, e.clientY);
        let timelinePosX = this.getPosXOnTimeline(pos.x);
        let newIndex = this.getIndexFromTimelinePosX(timelinePosX);
        this.moveTickImage(newIndex - this.tickImageIndex);
        console.log('tickImagetime',this.tickImageTime);
        this.$emit('timeline-tick-move',this.tickImageTime);
      },


      tickCanvasClickEvent(e) {
        let that = this;
        that.startPos = that.windowToCanvas(e.clientX, e.clientY);
        let tickImagePosX;
        let canvasPosX;
        let rect = {x: 0, y:0, w : 0, h : 0};

        let AtickImagePosX;
        let AcanvasPosX;
        let Arect={x:0,y:0,w:0,h:0};

        let BtickImagePosX;
        let BcanvasPosX;
        let Brect={x:0,y:0,w:0,h:0};

        if (this.showTwoTick) {
          AtickImagePosX = this.tickImageIndex * this.tickLineInterval;
          AcanvasPosX = this.getPosXOnCanvas(AtickImagePosX);
          Arect = {x: AcanvasPosX - this.ATickImage.width / 2, y:0, w : this.ATickImage.width, h : this.ATickImage.height};

          BtickImagePosX = this.BTickImageIndex * this.tickLineInterval;
          BcanvasPosX = this.getPosXOnCanvas(BtickImagePosX);
          Brect = {x: BcanvasPosX - this.BTickImage.width / 2, y:0, w : this.BTickImage.width, h : this.BTickImage.height};

          if (AcanvasPosX >= 0 && AcanvasPosX <= this.showRegionWidth && this.positionInRect(that.startPos, Arect)){
            that.ATickImageClicked = true;
            that.isBTickActive = false;
            that.ATickImage.src=that.AActiveTick;
            that.tickContext.drawImage(that.ATickImage,AcanvasPosX - that.ATickImage.width / 2 ,0);
            that.BTickImage.src=that.BDisabledTick;
            that.tickContext.drawImage(that.BTickImage,BcanvasPosX - that.BTickImage.width / 2 ,0);
            that.$emit('AB-compare-event','AIsActive');
          } else if (BcanvasPosX >= 0 && BcanvasPosX <= this.showRegionWidth && this.positionInRect(that.startPos, Brect)) {
            that.BTickImageClicked = true;
            that.isBTickActive = true;
            that.ATickImage.src=that.ADisabledTick;
            that.tickContext.drawImage(that.ATickImage,AcanvasPosX - that.ATickImage.width / 2 ,0);
            that.BTickImage.src=that.BActiveTick;
            that.tickContext.drawImage(that.BTickImage,BcanvasPosX - that.BTickImage.width / 2 ,0);
            that.$emit('AB-compare-event','BIsActive');
          } else{
            that.isMouseDown = true;
          }

        } else {
          tickImagePosX = this.tickImageIndex * this.tickLineInterval;
          canvasPosX = this.getPosXOnCanvas(tickImagePosX);
          rect = {x: canvasPosX - this.tickImage.width / 2, y:0, w : this.tickImage.width, h : this.tickImage.height};

          if (canvasPosX >= 0 && canvasPosX <= this.showRegionWidth && this.positionInRect(that.startPos, rect)){
            that.tickImageClicked = true;
          }else{
            that.isMouseDown = true;
          }
        }

      },

      //两个游标的时候，点击某个按钮改变游标的状态值
      changeABActive(AIsActive) {

        let AtickImagePosX = this.tickImageIndex * this.tickLineInterval;
        let AcanvasPosX = this.getPosXOnCanvas(AtickImagePosX);

        let BtickImagePosX = this.BTickImageIndex * this.tickLineInterval;
        let BcanvasPosX = this.getPosXOnCanvas(BtickImagePosX);

        let that = this;

        if (AIsActive) {
          that.ATickImage.src=that.AActiveTick;
          that.BTickImage.src=that.BDisabledTick;

        } else {
          that.ATickImage.src=that.ADisabledTick;
          that.BTickImage.src=that.BActiveTick;
        }
        setTimeout(function () {
          that.tickContext.drawImage(that.ATickImage,AcanvasPosX - that.ATickImage.width / 2 ,0);
          that.tickContext.drawImage(that.BTickImage,BcanvasPosX - that.BTickImage.width / 2 ,0);
        },100);

      },

      tickCanvasmousemoveEvent(e) {
        this.endPos=this.windowToCanvas(e.clientX, e.clientY);
        if (this.isMouseDown || this.tickImageClicked || this.ATickImageClicked || this.BTickImageClicked) {
          let dx = -(this.endPos.x - this.startPos.x);
          //console.log('dx: ',dx);

          if (this.isMouseDown) {
            this.moveTimeline(dx);
          }else if(this.tickImageClicked) {
            let timelinePosX = this.getPosXOnTimeline(this.endPos.x);
            let newIndex = this.getIndexFromTimelinePosX(timelinePosX);

            this.moveTickImage(newIndex - this.tickImageIndex);

          } else if (this.ATickImageClicked) {
            let timelinePosX = this.getPosXOnTimeline(this.endPos.x);
            let newIndex = this.getIndexFromTimelinePosX(timelinePosX);

            this.moveTickImage(newIndex - this.tickImageIndex);
          } else if (this.BTickImageClicked) {
            let timelinePosX = this.getPosXOnTimeline(this.endPos.x);
            let newIndex = this.getIndexFromTimelinePosX(timelinePosX);

            this.moveTickImage(newIndex - this.BTickImageIndex);
          }
          this.startPos.x = this.endPos.x;
        }else{
          let timelinePosX = this.getPosXOnTimeline(this.endPos.x);
          let index = this.getIndexFromTimelinePosX(timelinePosX);

        }
      },

      tickCanvasmouseupEvent(e) {
        //console.log(222);
        this.endPos=this.windowToCanvas(e.clientX, e.clientY);
        this.isMouseDown = false;
        if (this.tickImageClicked) {
          this.$emit('timeline-tick-move',this.tickImageTime);
          this.tickImageClicked = false;
        }

        if (this.ATickImageClicked) {
          this.$emit('timeline-tick-move',this.tickImageTime);
          this.ATickImageClicked = false;
        }

        if (this.BTickImageClicked) {
          this.$emit('timeline-tick-move',this.BTickImageTime);
          this.BTickImageClicked = false;
        }

      },

      tickCanvasmousewheelEvent(e) {
        let current = this.currentScale;
        let mousePos = this.windowToCanvas(e.clientX, e.clientY);
        let det = Math.floor(e.wheelDelta / 100);
        //console.log("Monse wheel : " +det);
        if (det == 0) return;
        if (det > 0) det = 1;
        if (det < 0) det = -1;
        let that = this;
        setTimeout(function () {
          that.scaleTimeline(current + det);

          if (that.currentScale == 1) {
            that.whatTimeInterval = 'Year';
          } else if (that.currentScale == 2) {
            that.whatTimeInterval = 'Season';
          } else if (that.currentScale == 3) {
            that.whatTimeInterval = 'Month';
          }else if (that.currentScale == 4) {
            that.whatTimeInterval = 'Week';
          }else if (that.currentScale == 5) {
            that.whatTimeInterval = 'Day';
          }
        },200);

        e.stopPropagation();
        e.preventDefault();
      },

      windowToCanvas(x, y) {
        //获取当前鼠标在window中的坐标值
        //alert(event.clientX+"-------"+event.clientY);
        // 获取元素的坐标属性
        var box = this.tickCanvas.getBoundingClientRect();
        var bx = x - box.left;
        var by = y - box.top;
        return {x: bx, y: by};
      },


      //设置canvas的宽高
      setCanvasWH(width,height) {
        //this.canvas.width = width;
        //this.canvas.height = height;

        this.tickCanvas.width = width;
        this.tickCanvas.height = height;

        this.drawTimeTick();
      },


      changeDate(date,type) {
       this.$emit('date-change',{type:type,date:date});
       if (type == 'start') {
         this.tickImageTime = date;
         this.drawTimeTick();
       }
      },

      //时间间隔的选择
      intervalSelect(e) {
        this.whatTimeInterval = e;
        this.judgeWhatInterval();
      },

      stopPlayTimeLine() {
        if (this.isPlay){
          this.isPlay = false;
          clearInterval(this.timeInterval);
          this.playTimeIsChange = true;
          this.$emit('stop-play','');
        }
      },

      getMoveStep() {
        if (this.currentScale == 4) return 7;
        return 1;
      },

      //播放按钮的响应函数
      playTime() {
        this.whatScene=='layer'?this.preparePlayData():this.playTimeLine();
      },

      //图层场景中时间轴的播放 准备播放的数据，返回播放的数据
      preparePlayData() {

        if (this.isTwoTick) return;

        if (this.playStartT == '') {
          this.$emit('timeline-play',[]);
          return;
        }

        this.isPlay = !this.isPlay;
        if (!this.isPlay) {
          this.$emit('timeline-play',[]);
          return;
        }

        if (this.isFirstClickPlay || this.playTimeIsChange) {  //重新获取数据用于播放
          let timeList = [];

          let startResult =  this.getYMDFromString(this.playStartT);
          let endResult =  this.getYMDFromString(this.playEndT);
          let startImageIndex = this.getIndexFromYMD(startResult.year,startResult.month,startResult.day);
          let endImageIndex = this.getIndexFromYMD(endResult.year,endResult.month,endResult.day);

          let check = this.getTimeFromIndex(startImageIndex);
          if (check.year != startResult.year || check.month != startResult.month || check.day != startResult.day) {
            startImageIndex += this.getMoveStep();
          }

          for (var i = startImageIndex; i <= endImageIndex; i += this.getMoveStep()){
            let result = this.getTimeFromIndex(i);
            let tickImageTime = result.year + '-' +(result.month<10?'0'+result.month:result.month)+'-' +(result.day<10?'0'+result.day:result.day);
            timeList.push(tickImageTime);
          }

          if (this.playTimeIsChange) this.playTimeIsChange= false;

          this.$emit('timeline-play',timeList);
          this.isFirstClickPlay = false;
        } else {                                   //暂停之后继续播放
          this.$emit('timeline-play',[]);
        }

      },

      moveTickImageFromTimeString(str) {
        let time =  this.getYMDFromString(str);
        if (time == 0) return;
        let index = this.getIndexFromYMD(time.year,time.month,time.day);
        this.moveTickImage(index - this.tickImageIndex);
      },


      //产品场景中时间轴的播放 播放时间轴
      /*playTimeLine() {

        let that = this;
        this.isPlay = !this.isPlay;
        if (this.isPlay) {

          let startResult =  this.getYMDFromString(this.layerList[this.productPlayIndex].timeRange[0].startTime);
          //let endResult =  this.getYMDFromString(this.endTime);

          let startImageIndex = this.getIndexFromYMD(startResult.year,startResult.month,startResult.day);
          //let endImageIndex = this.getIndexFromYMD(endResult.year,endResult.month,endResult.day);

          let check = this.getTimeFromIndex(startImageIndex);
          if (check.year != startResult.year || check.month != startResult.month || check.day != startResult.day) {
            startImageIndex += this.getMoveStep();
          }

          //if (startImageIndex == endImageIndex) return;

          this.moveTickImage(startImageIndex - this.tickImageIndex);

          this.$emit('timeline-play',{index:this.productPlayIndex,layer:this.layerList[this.productPlayIndex]});

          this.timeInterval = setInterval(function () {
            that.productPlayIndex++;
            if (that.productPlayIndex >= that.layerList.length) that.productPlayIndex = 0;
            let endResult = that.getYMDFromString(that.layerList[that.productPlayIndex].timeRange[0].startTime);
            let endImageIndex = that.getIndexFromYMD(endResult.year,endResult.month,endResult.day);
            that.moveTickImage(endImageIndex - that.tickImageIndex);
            that.$emit('timeline-play',{index:that.productPlayIndex,layer:that.layerList[that.productPlayIndex]});
          },1000);
        } else {
          clearInterval(this.timeInterval);
          //this.productPlayIndex = 0;
        }

      },*/

      //时间轴播放函数
      playTimeLine() {

        let that = this;
        this.isPlay = !this.isPlay;
        if (this.isPlay) {

          let startResult =  this.getYMDFromString(this.startTime);
          let endResult =  this.getYMDFromString(this.endTime);

          let startImageIndex = this.getIndexFromYMD(startResult.year,startResult.month,startResult.day);
          let endImageIndex = this.getIndexFromYMD(endResult.year,endResult.month,endResult.day);

          let check = this.getTimeFromIndex(startImageIndex);
          if (check.year != startResult.year || check.month != startResult.month || check.day != startResult.day) {
            startImageIndex += this.getMoveStep();
          }

          if (startImageIndex == endImageIndex) return;

          this.moveTickImage(startImageIndex - this.tickImageIndex);
          this.$emit('timeline-play',this.tickImageTime);

          this.timeInterval = setInterval(function () {
            if (that.tickImageIndex > endImageIndex) {
              that.moveTickImage(startImageIndex - that.tickImageIndex);
              that.$emit('timeline-play',that.tickImageTime);
            }else {
              that.moveTickImage(that.getMoveStep());
              that.$emit('timeline-play',that.tickImageTime);
            }
          },1000);
        } else {
          clearInterval(this.timeInterval);
        }

      },


    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  @import "../../../assets/styles/base_style";
  #timeline-wrapper {
    width: 100%;
    height: 120px;
    background: rgba(17, 18, 19, 0.7);
    padding: 10px;
  }
  #timeLine_content {
    width:100%;
    height:100%;
    display: flex;
    .timeline-header {
      float:left;
      width:300px;
      height:100%;
      border-right:1px solid #2b488f;
      .now-time {
        float:left;
        width:195px;
        height:100%;
        .now-word {
          float:left;
          height:30px;
          margin-top:35px;
          margin-right:17px;
          @include fontSize(24px, #fff,bold);
        }
        .now-year {

        }
        .now-month {

        }
        .now-day {

        }
      }
      .play-content {
        float:left;
        width:100px;
        height:100%;
        .now-time-interval {
          width:100%;
          height:22px;
          margin:19px 0 10px 0;
          text-align: center;
          @include fontSize(10px, #fff, '');
          .el-dropdown {
            color:#fff;
          }
        }
        .play-btn {
          width:38px;
          height:30px;
          margin:0 auto;
          background:url(./image/play-btn.png) 0 0 no-repeat;
        }
        .pause-btn {
          background:url(./image/pause-btn.png) 0 0 no-repeat;
        }
        .hide-play-btn {
          background:url(./image/play-disabled.png) 0 0 no-repeat;
        }
      }
    }
    .now-time-select {
      float:left;
      width:100px;
      height:100%;
      .el-input {
        background-color:rgba(17, 18, 19, 0.7);
        .el-input__inner {
          background:none;
          border:none;
          @include fontSize(10px, #fff,bold);
          padding-left:25px;
          padding-right:5px;
        }
        .el-input__icon {
          width:20px;
          left:8px;
        }
        .el-input__prefix {
          @include fontSize(10px, #fff,bold);
        }
      }
    }
    .draw-time-line {
      position:relative;
      float:left;
      width:calc(100% - 203px - 300px);
      height:100%;
      border-left:1px solid #484649;
      border-right:1px solid #484649;
      overflow:hidden;
     /* overflow-x:auto;
      overflow-y:hidden;*/
      .time-line-canvas {
        position: absolute;
        transform:translate(0px,0px);
        z-index:10000000;
      }
      .little-tick-canvas {
        position:absolute;
      }

    }
  }
</style>
